import Taro from '@tarojs/taro-rn';
import * as tslib_1 from "tslib";
import React from 'react';
import { Component } from "@tarojs/taro-rn";
import { QRCode } from 'taro-code';
import { inject, observer } from "@tarojs/mobx-rn";
import html2canvas from 'html2canvas';
import { View, Image } from "@tarojs/components-rn";
import { getRuntime, ServerHost } from "../../utils/common";
import qrcodeStyleSheet from "./qrcode_styles";

import bg_19_2 from "../../assets/img/bg_19_3.png";
var _styleSheet = qrcodeStyleSheet;
let Company = class Company extends Component {
  constructor(props) {
    super(props);

    this.getJsApiParam = () => {
      let currentUrl = window.location.href;
      let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`;
      Taro.showLoading({ title: '加载中...' });
      fetch(apiUrl, {
        method: 'GET',
        mode: "cors",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        credentials: 'same-origin'
      }).then(response => {
        Taro.hideLoading();
        return response.json();
      }).then(response => {
        let appId = response.appId;
        let timestamp = response.timestamp;
        let nonceStr = response.nonceStr;
        let signature = response.signature;
        wx.config({
          debug: false,
          appId: appId,
          timestamp: timestamp,
          nonceStr: nonceStr,
          signature: signature,
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      }).catch(error => {
        console.log(error);
      });
    };

    this.html2Canvas = () => {
      let shareContent = document.getElementById('my_my_code'); //需要截图的包裹的（原生的）DOM 对象
      let width = shareContent.offsetWidth; //获取dom 宽度
      let height = shareContent.offsetHeight; //获取dom 高度
      let canvas = document.createElement("canvas"); //创建一个canvas节点
      let scale = 5; //定义任意放大倍数 支持小数
      canvas.width = width * scale; //定义canvas 宽度 * 缩放
      canvas.height = height * scale; //定义canvas高度 *缩放
      canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
      let opts = {
        scale: scale,
        logging: true,
        width: width,
        height: height,
        backgroundColor: 'transparent',
        useCORS: true,
        allowTaint: true,
        logging: false
      };
      const that = this;
      Taro.showLoading({ title: '海报生成中...' });
      html2canvas(shareContent, opts).then(canvas => {
        Taro.hideLoading();
        this.setState({ isShow: true });
        let shareImgSrc = canvas.toDataURL("image/png");
        that.setState({ shareImgSrc: shareImgSrc });
      });
    };

    this.state = {
      userInfo: null,
      invitationCode: null,
      shareImgSrc: '',
      isShow: false
    };
    // 配置微信分享
  }
  componentWillMount() {
    Taro.setNavigationBarTitle({ title: '我的二维码' });
    let userInfo = getRuntime().getUserInfo();
    this.getInvitationCode(userInfo.id.toString());
    this.setState({
      userInfo
    });
  }
  componentDidMount() {
    this.getJsApiParam();
  }
  componentDidShow() {
    this.share();
  }
  getInvitationCode(userId = '') {
    let len = userId.length;
    let res = userId;
    if (len < 5) {
      res = new Array(5 - len).fill(0).join('') + userId;
    }
    this.setState({ invitationCode: res });
  }
  handelRouter(url = '/pages/index/index') {
    getRuntime().navigateTo(url);
  }
  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let { userInfo } = this.state;
    let url = `${ServerHost}/m/#/pages/login/register_step_one?invitationCode=${userInfo.id}`;
    let title = '建务通工程保证担保解决方法服务提供商, 为你保驾护航!';
    let desc = '快来加入我们吧~';
    let imgUrl = `${ServerHost}/m/logo.png`;
    var shareData = {
      title,
      desc,
      imgUrl,
      url,
      link: url
    };
    wx.ready(function () {
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
    // WxShare(url,item.logo,item.title,partOf(item.content, 30))
  }
  close(e) {
    e.preventDefault();
    e.stopPropagation();
    this.setState({ isShow: false });
  }
  render() {
    let { userInfo, invitationCode, shareImgSrc, isShow } = this.state;
    console.log(userInfo);
    return <View>
        <View id="my_my_code" onClick={this.html2Canvas.bind(this)} style={_styleSheet["my-my_code"]}>
          <Image src={bg_19_2} style={_styleSheet["bg"]} />
          <View style={_styleSheet["header"]}>
          </View>
          <View style={_styleSheet["main"]}>
            <View style={_styleSheet["info"]}>
              <View style={_styleSheet["name"]}>{userInfo.name}</View>
              <View style={_styleSheet["img-code"]}>
                <QRCode text={ServerHost + '/m/#/pages/login/register_step_one?invitationCode=' + userInfo.id} size={145} />
              </View>
              <View style={_styleSheet["code"]}>邀请码： {invitationCode}</View>
            </View>
          </View>
        </View>
        {isShow && <View onClick={this.close.bind(this)} style={_styleSheet["share-img"]}>
           <Image src={shareImgSrc} style={[_styleSheet["img"], _styleSheet["img-active"]]} />
           <View style={_styleSheet["tipsText"]}>长按保存图片、识别二维码</View>
        </View>}
      </View>;
  }
};
Company = tslib_1.__decorate([inject("stores"), observer], Company);
export default Company;